/* Copyright (c) 2022 渝州大数据实验室
 *
 * Lanius is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *
 *     http://license.coscl.org.cn/MulanPSL2
 *
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 */
package org.yzbdl.lanius.orchestrate.common.jwt;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.springframework.beans.factory.annotation.Value;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.Map;

/**
 * jwt辅助类
 *
 * @author chenjunhao@yzbdl.ac.cn
 * @date 2022-04-18 16:23
 */
public class JwtHelper {


	/**
	 * 从request中获取token值
	 * @param request 请求对象
	 * @return token值
	 */
	public static String getTokenFromRequest(HttpServletRequest request){
		String authHeader = request.getHeader(JwtConst.AUTHORIZATION);
		if(authHeader != null && authHeader.startsWith(JwtConst.TOKEN_HEADER)){
			return authHeader.substring(JwtConst.TOKEN_HEADER.length()).strip();
		}
		return "";
	}

	/**
	 * 从令牌转换为声明对象
	 * @param token 令牌
	 * @param secret 口令
	 * @return 声明map
	 */
	public static Map<String,Object> getClaimMap(String token, String secret){
		try{
			JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(secret)).build();
			DecodedJWT decodedJwt = jwtVerifier.verify(token);
			if(decodedJwt.getExpiresAt().after(new Date())){
				return decodedJwt.getClaim(JwtConst.CLAIM_KEY).asMap();
			}
		}catch (Exception ignored){}
		return null;
	}

	/**
	 * 从令牌转换为声明对象(普通用户)
	 * @param token 令牌
	 * @return 声明map
	 */
	public static Map<String,Object> getNormalClaimMapFromToken(String token) {
		return getClaimMap(token,JwtConst.NORMAL_SECRET);
	}

	/**
	 * 从令牌转换为声明对象(管理员用户)
	 * @param token 令牌
	 * @return 声明map
	 */
	public static Map<String,Object> getManagerClaimMapFromToken(String token) {
		return getClaimMap(token,JwtConst.MANAGER_SECRET);
	}


	/**
	 * 将需要的有效的小时转为具体的日期
	 * @param hour 小时数
	 * @return 具体日期
	 */
	public static Date toDateByHour(int hour){
		return new Date(System.currentTimeMillis() + (long) hour * 3600 * 1000);
	}

}
